<template>
  <div class="p-6">
    <h1 class="text-2xl font-bold mb-4">多用户多设备测试</h1>
    
    <!-- 会话信息 -->
    <div class="mb-4 p-4 bg-blue-50 rounded">
      <h3 class="font-semibold mb-2">当前会话信息</h3>
      <div class="text-sm space-y-1">
        <div>会话ID: {{ sessionId }}</div>
        <div>WebSocket状态: {{ isConnected ? '已连接' : '未连接' }}</div>
        <div>录音状态: {{ isRecording ? '录音中' : '未录音' }}</div>
        <div>阿里云连接: {{ hasAliyunClient ? '已连接' : '未连接' }}</div>
      </div>
    </div>
    
    <!-- 设备选择 -->
    <div class="mb-4">
      <h3 class="text-lg font-semibold mb-2">选择目标设备</h3>
      <select v-model="selectedDevice" class="w-full p-2 border rounded">
        <option value="">请选择设备</option>
        <option v-for="device in devices" :key="device.deviceId" :value="device.deviceId">
          {{ device.deviceName || device.deviceId }}
        </option>
      </select>
    </div>
    
    <!-- 录音控制 -->
    <div class="mb-4">
      <button 
        @click="toggleRecording" 
        :disabled="!selectedDevice"
        class="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
      >
        {{ isRecording ? '停止录音' : '开始录音' }}
      </button>
    </div>
    
    <!-- 识别结果 -->
    <div v-if="result" class="mb-4 p-4 bg-green-100 rounded">
      <h3 class="font-semibold">识别结果:</h3>
      <p>{{ result }}</p>
      <p class="text-sm">置信度: {{ (confidence * 100).toFixed(1) }}%</p>
    </div>
    
    <!-- 实时日志 -->
    <div class="mb-4 p-4 bg-gray-50 rounded">
      <h3 class="font-semibold mb-2">实时日志</h3>
      <div class="text-sm max-h-40 overflow-y-auto">
        <div v-for="(log, index) in logs" :key="index" class="mb-1">
          <span class="text-gray-500">{{ log.timestamp }}</span>
          <span :class="log.type === 'error' ? 'text-red-600' : 'text-gray-700'">
            {{ log.message }}
          </span>
        </div>
      </div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="flex space-x-2">
      <button @click="loadDevices" class="px-4 py-2 bg-gray-500 text-white rounded">
        刷新设备
      </button>
      <button @click="connectWebSocket" :disabled="isConnected" class="px-4 py-2 bg-green-500 text-white rounded disabled:opacity-50">
        连接WebSocket
      </button>
      <button @click="disconnectWebSocket" :disabled="!isConnected" class="px-4 py-2 bg-red-500 text-white rounded disabled:opacity-50">
        断开连接
      </button>
      <button @click="clearLogs" class="px-4 py-2 bg-yellow-500 text-white rounded">
        清空日志
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { deviceAPI } from '@/services/api';
import { voiceWebSocket, type VoiceRecognitionMessage } from '@/services/websocket';

const devices = ref<any[]>([]);
const selectedDevice = ref('');
const isRecording = ref(false);
const isConnected = ref(false);
const hasAliyunClient = ref(false);
const result = ref('');
const confidence = ref(0);
const sessionId = ref('');
const logs = ref<Array<{timestamp: string, message: string, type: string}>>([]);

let mediaRecorder: MediaRecorder | null = null;

onMounted(async () => {
  sessionId.value = `mobile_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  await loadDevices();
  await connectWebSocket();
});

onUnmounted(() => {
  if (mediaRecorder && isRecording.value) {
    mediaRecorder.stop();
  }
  voiceWebSocket.disconnect();
});

const addLog = (message: string, type: string = 'info') => {
  const timestamp = new Date().toLocaleTimeString();
  logs.value.push({ timestamp, message, type });
  if (logs.value.length > 50) {
    logs.value.shift();
  }
};

const clearLogs = () => {
  logs.value = [];
};

const loadDevices = async () => {
  try {
    devices.value = await deviceAPI.getUserDevices();
    addLog(`加载设备列表成功，共 ${devices.value.length} 个设备`);
  } catch (error) {
    addLog(`加载设备失败: ${error}`, 'error');
  }
};

const connectWebSocket = async () => {
  try {
    await voiceWebSocket.connect();
    isConnected.value = true;
    addLog('WebSocket连接成功');
    
    voiceWebSocket.onMessage((message: VoiceRecognitionMessage) => {
      addLog(`收到消息: ${message.type}`, 'info');
      
      switch (message.type) {
        case 'device_selected':
          if (message.success) {
            addLog(`设备选择成功: ${message.deviceId}`);
          }
          break;
          
        case 'recognition_started':
          if (message.success) {
            addLog('语音识别已开始');
            hasAliyunClient.value = true;
          }
          break;
          
        case 'recognition_result':
          if (message.success && message.text) {
            result.value = message.text;
            confidence.value = message.confidence || 0;
            addLog(`识别结果: ${message.text}`);
          }
          break;
          
        case 'recognition_stopped':
          if (message.success) {
            addLog('语音识别已停止');
            hasAliyunClient.value = false;
          }
          break;
          
        case 'error':
          addLog(`识别错误: ${message.error}`, 'error');
          break;
      }
    });
    
    voiceWebSocket.onError((error: string) => {
      addLog(`WebSocket错误: ${error}`, 'error');
    });
    
    voiceWebSocket.onConnect(() => {
      isConnected.value = true;
      addLog('WebSocket连接已建立');
    });
    
    voiceWebSocket.onDisconnect(() => {
      isConnected.value = false;
      hasAliyunClient.value = false;
      addLog('WebSocket连接已断开');
    });
    
  } catch (error) {
    addLog(`连接失败: ${error}`, 'error');
  }
};

const disconnectWebSocket = () => {
  voiceWebSocket.disconnect();
  isConnected.value = false;
  hasAliyunClient.value = false;
  addLog('WebSocket连接已断开');
};

const toggleRecording = async () => {
  if (isRecording.value) {
    stopRecording();
  } else {
    startRecording();
  }
};

const startRecording = async () => {
  try {
    if (!selectedDevice.value) {
      addLog('请先选择目标设备', 'error');
      return;
    }
    
    addLog(`开始录音，目标设备: ${selectedDevice.value}`);
    
    voiceWebSocket.selectDevice(selectedDevice.value);
    voiceWebSocket.startRecognition();
    
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    mediaRecorder = new MediaRecorder(stream);
    
    mediaRecorder.ondataavailable = (event) => {
      if (event.data.size > 0) {
        voiceWebSocket.sendAudioData(event.data);
      }
    };
    
    mediaRecorder.onstart = () => {
      isRecording.value = true;
      addLog('录音已开始');
    };
    
    mediaRecorder.onstop = () => {
      voiceWebSocket.stopRecognition();
      stream.getTracks().forEach(track => track.stop());
      isRecording.value = false;
      addLog('录音已停止');
    };
    
    mediaRecorder.start(200);
  } catch (error) {
    addLog(`录音失败: ${error}`, 'error');
  }
};

const stopRecording = () => {
  if (mediaRecorder && isRecording.value) {
    mediaRecorder.stop();
  }
};
</script>
